﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Xaml;

namespace VivendoByteToolkit.Helpers
{
    public class TapCommandHelper
    {
        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached("Command",
            typeof(ICommand),
            typeof(TapCommandHelper),
            new PropertyMetadata(null,
            new PropertyChangedCallback(Setup)));

        private static void Setup(DependencyObject obj,
            DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement ctl = obj as FrameworkElement;

            if (ctl != null)
            {
                ICommand oldValue = (ICommand)e.OldValue;
                ICommand newValue = (ICommand)e.NewValue;

                if (oldValue == null && newValue != null)
                {
                    {
                        ctl.Tapped += ctl_Tapped;
                    }
                }
                else if (oldValue != null && newValue == null)
                {
                    ctl.Tapped -= ctl_Tapped;
                }
            }
        }

        static void ctl_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            var element = sender as FrameworkElement;
            var command = GetCommand(element);

            if (command != null)
            {
                if (command.CanExecute(null))
                {
                    command.Execute(null);
                }
            }
        }
    }
}